<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归属商家" prop="name">
        <el-input
          v-model="queryParams.storeId"
          placeholder="请输入归属商家ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品ID" prop="name">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入商品ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择审核状态"
          clearable
          size="small"
        >
          <el-option
            label="请选择审核状态"
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="display: block">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ds:store:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ds:store:edit']"
          >审核</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ds:store:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ds:product:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="storeList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="id" />
      <el-table-column label="商品名" align="center" prop="name" width="200" />
      <el-table-column label="商品图片" align="center" prop="image" width="150">
        <template slot-scope="scope">
          <img
            style="width: 80px; height: 80px; border: none"
            :src="scope.row.image"
          />
        </template>
      </el-table-column>
      <el-table-column label="商家ID" align="center" prop="storeId">
        <template slot-scope="scope">
          <el-link type="primary" @click="showStore(scope.row.storeId)">{{
            scope.row.storeId
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="进价" align="center" prop="price" />
      <el-table-column label="售价" align="center" prop="vipPrice" />
      <el-table-column label="利润" align="center" prop="postage" />
      <el-table-column label="贡献值" align="center" prop="quota" />
      <el-table-column label="赠送倍数" align="center" prop="giftAmount" />
      <el-table-column label="销量" align="center" prop="sales" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="审核状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 3" type="warning">待审核</el-tag>
          <el-tag v-else type="success">已审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="添加时间"
        align="center"
        prop="createTime"
        class-name="small-padding fixed-width"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="上架/下架"
        align="center"
        class-name="small-padding fixed-width"
        width="100"
      >
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status"
            inactive-color="#13ce66"
            active-color="#ff4949"
            :active-value="0"
            :inactive-value="1"
            @change="statusChecked($event, scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            v-if="scope.row.status == 3"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ds:products:edit']"
            >审核</el-button
          >
          <el-button
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ds:products:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改商品信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-bod
      :close-on-click-modal="false"
      @close="dialogClosed"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品图片" prop="image">
          <imageUpload v-model="form.image" />
        </el-form-item>
        <!-- <el-form-item label="轮播图" prop="sliderImage">
          <imageUpload v-model="form.sliderImage"/>
        </el-form-item> -->
        <el-form-item label="轮播图" prop="sliderImage">
          <el-upload
            :action="uploadImgUrl"
            :file-list="filesList"
            ref="upload"
            list-type="picture-card"
            :limit="4"
            @submit.native.prevent
            :headers="headers"
            :show-file-list="true"
            :on-change="fileChange"
            :on-remove="fileRemove"
            :on-success="handleUploadSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品名" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名" />
        </el-form-item>
        <el-form-item label="商品简介">
          <editor v-model="form.info" :min-height="192" />
        </el-form-item>
        <el-form-item label="关键字" prop="keyword">
          <el-input v-model="form.keyword" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="商家ID" prop="storeId">
          <el-input
            v-model.number="form.storeId"
            placeholder="请输入商家ID"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类id" prop="cateId">
          <!-- <el-input v-model="form.cateId" placeholder="请输入分类id" /> -->

          <el-select
            v-model="form.cateId"
            placeholder="请选择分类"
            clearable
            size="small"
            style="width: 100%"
          >
            <el-option
              label="请选择字典生成"
              v-for="item in categoryList"
              :key="item.id"
              :label="item.cateName + '-' + item.id"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="进价" prop="price">
          <el-input v-model="form.price" placeholder="请输入进价" />
        </el-form-item>
        <el-form-item label="售价" prop="vipPrice">
          <el-input v-model="form.vipPrice" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="利润" prop="postage">
          <div style="font-weight: 600; font-size: 18px">
            {{
              Number.parseFloat(form.vipPrice) -
                Number.parseFloat(form.price) || "0"
            }}
          </div>
          <!--          <el-input :disabled="true" v-model="form.vipPrice" placeholder="请输入计算利润" />-->
          <!-- <el-input  v-model="form.postage" placeholder="请输入利润" /> -->
        </el-form-item>
        <el-form-item label="赠送倍数" prop="giftAmount">
          <!-- <el-form-item>{{form.quota/form.postage}}</el-form-item> -->
          <el-input
            v-model.number="form.giftAmount"
            placeholder="请输入赠送倍数"
          />
        </el-form-item>
        <el-form-item label="销量" prop="sales">
          <el-input v-model.number="form.sales" placeholder="请输入销量" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model.number="form.stock" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="贡献值" prop="quota">
          <el-input v-model="form.quota" placeholder="请输入贡献值" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入序号" />
        </el-form-item>
        <el-form-item label="是否事业" prop="isBiz">
          <!-- <el-input v-model="form.isBiz" placeholder="现金为1，积分为0" /> -->
          <el-switch
            v-model="form.isBiz"
            inactive-text="否"
            :inactive-value="0"
            :active-value="1"
            active-text="是"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="是否限购" prop="isLimit">
          <!-- isLimit 0不限购，1限购。 limitNum：限购数量 -->
          <el-row>
            <el-col :span="8">
              <el-switch
                v-model="form.isLimit"
                inactive-text="不限"
                active-text="限购"
                :inactive-value="0"
                :active-value="1"
                active-color="#ff4949"
                inactive-color="#13ce66"
              >
              </el-switch>
            </el-col>
            <el-col :span="16" v-show="form.isLimit == 1">
              <div style="width: 20%; display: inline-block">限购数量：</div>
              <el-input
                type="number"
                v-model.number="form.limitNum"
                placeholder="请输入限购数量"
                style="width: 80%"
              />
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="混合支付">
          <div>
            <el-switch
              v-model="isBlend"
              inactive-text="否"
              active-text="是"
              @change="payTypeChanged"
            >
            </el-switch>
          </div>
          <el-row v-show="isBlend" style="margin-top: 1%">
            <el-col :span="8" style="display: flex">
              现金比例：
              <el-input
                :value="form.cashRatio"
                style="width: 50%"
                :disabled="true"
              />%
            </el-col>
            <el-col :span="8" style="display: flex">
              gtfy比例：
              <el-input
                v-model="form.passProportion"
                style="width: 50%"
                @input="gtfyInputChanged"
              />%
            </el-col>
            <el-col :span="8" style="display: flex">
              <el-input-number
                v-model="form.passProportion"
                :min="0"
                :max="100"
                width="100"
                @change="gtfyChanged"
              >
              </el-input-number
              >%
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="实际支付">
          <el-row>
            <el-col :span="2" style="border: 1px solid transparent"></el-col>
            <el-col v-if="form.cashRatio" :span="7">
              <div class="actualPay" style="width: 37%">
                ￥{{ (form.vipPrice * form.cashRatio) / 100 }}
              </div>
            </el-col>
            <el-col v-else :span="7">
              <div class="actualPay" style="width: 37%">
                ￥{{ form.vipPrice }}
              </div>
            </el-col>
            <el-col :span="14">
              gtfy
              <div class="actualPay" style="width: 18%; margin-left: 3%">
                {{ (form.vipPrice * form.passProportion) / 100 }}
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <!-- <el-form-item label="现金" prop="quota">
          <el-input v-model="form.cashRatio" placeholder="请输入贡献值" />
        </el-form-item> -->
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="source">
          <el-input v-model="form.source"></el-input>
        </el-form-item> -->

        <el-form-item label="规格设置">
          <SkuChoice
            :price="form.price"
            :vipPrice="form.vipPrice"
            :giftAmount="form.giftAmount"
            :size="form.size"
            @submit="handleSubmit"
          >
          </SkuChoice>
        </el-form-item>
        <el-row>
          <el-col :span="20">
            <el-form-item label="备注">
              <editor v-model="form.offShelfReason" :min-height="130" />
            </el-form-item>
          </el-col>
          <el-col :span="4" style="color: red">
            (开发者寄语)
            审核人员请注意，如您拒绝通过，请再原备注另起一行，确保输入原因，再点击拒绝按钮
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="pass">通 过</el-button>
        <el-button type="danger" @click="refuse">拒 绝</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProducts,
  getProducts,
  delProducts,
  addProducts,
  updateProducts,
  exportProducts,
  specification,
} from "@/api/ds/products";
import { listCategory } from "@/api/ds/category";
import ImageUpload from "@/components/ImageUpload";
import ImagesUpload from "@/components/ImagesUpload";
import Editor from "@/components/Editor";
import { getToken } from "@/utils/auth";
import SkuChoice from "../product/components/SkuChoice.vue";
import { getStore } from "@/api/ds/store";
export default {
  name: "Products",
  components: {
    ImageUpload,
    ImagesUpload,
    Editor,
    SkuChoice,
  },
  data() {
    var validateID = (rule, value, callback) => {
      if (value) {
        if (!/^([1-9][0-9]*){1,3}$/.test(value)) {
          callback(new Error("请输入正确的值"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入值"));
      }
    };
    var validatePrice = (rule, value, callback) => {
      if (value) {
        if (!/^([1-9][0-9]*)+(.[0-9]{1,2})?$/.test(value)) {
          callback(new Error("请输入正确的价格（最多两位小数）"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入价格"));
      }
    };
    return {
      mode: "",
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/uploadImage", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      filesList: [],
      categoryList: [], // 分类列表
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: null, //商品商家id
        // source: 2, //商品来源1.自营 2.商家(传2)
        storeName: null,
        goodsStatus: null,
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        size: null,
        storeId: "",
      },
      // 表单校验
      rules: {
        image: [{ required: true, message: "商品图不能为空", trigger: "blur" }],
        sliderImage: [
          { required: true, message: "轮播图不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "商品名不能为空", trigger: "blur" }],
        cateId: [{ required: true, validator: validateID, trigger: "blur" }],
        storeId: [
          { required: true, message: "商家ID不能为空", trigger: "blur" },
        ],
        price: [{ required: true, message: "进价不能为空", trigger: "blur" }],
        vipPrice: [
          { required: true, message: "售价不能为空", trigger: "blur" },
        ],
        sales: [{ required: true, message: "销量不能为空", trigger: "blur" }],
        stock: [{ required: true, message: "库存不能为空", trigger: "blur" }],
        quota: [{ required: true, message: "贡献值不能为空", trigger: "blur" }],
        giftAmount: [
          { required: true, message: "赠送倍数不能为空", trigger: "blur" },
        ],
        limitNum: [
          { required: true, message: "限购数量不能为空", trigger: "blur" },
        ],
      },
      isMixPay: false, // 是否混合支付
      isBlend: false,
      statusOptions: [
        // 分类下拉框
        {
          value: "1",
          label: "上架",
        },
        {
          value: "0",
          label: "下架",
        },
      ],
    };
  },
  created() {
    this.getList();
    this.getCateList();
  },

  methods: {
    async showStore(id) {
      await getStore(id).then((res) => {
        if (res.code === 200) {
          this.$alert(
            `店铺名称: ${res.data.name}<br> 姓名:${res.data.legalPerson}<br> 手机号:${res.data.telephone}`,
            "店铺信息",
            {
              confirmButtonText: "确定",
              dangerouslyUseHTMLString: true,
            }
          );
        }
      });
    },
    handleSubmit(ids) {
      this.$set(this.form, "size", ids.join(","));
    },
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      // specification(this.queryParams2).then(res => {
      // })
      // return

      listProducts(this.queryParams).then((response) => {
        // this.storeList = response.rows;

        this.$set(this, "storeList", response.rows);
        this.$forceUpdate();

        this.total = response.total;
        this.loading = false;
      });
    },
    getCateList() {
      listCategory().then((response) => {
        this.categoryList = response.rows.filter((item) => {
          return item.id > 200 && item.id < 300;
        });
      });
    },
    dialogClosed() {
      this.open = false;
      this.$refs.upload.clearFiles(); // 取消按钮也要清一遍轮播图
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 操作上下架switch按钮
    statusChecked(e, row) {
      row.status = e;
      updateProducts(row).then((response) => {
        this.msgSuccess("修改成功");
        this.getList();
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isMixPay = false;
      this.open = true;
      this.title = "添加商家信息";

      this.mode = "add";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      const _this = this;

      this.mode = "edit";
      this.reset();
      const id = row.id || this.ids;
      let response = await getProducts(id);
      this.filesList = response.data.sliderImage.split(",").map((item) => {
        return { url: item, name: item };
      });

      this.form = response.data;
      if (!this.form.isBlend) {
        this.isBlend = false;
      }
      if (this.form.isBlend == 0) {
        this.isBlend = true;
      }
      if (this.form.isBlend == 1) {
        this.isBlend = false;
      }

      this.open = true;
      this.title = "审核商家";
    },
    gtfyChanged(value) {
      if (value) {
        this.form.passProportion = value;
        this.form.cashRatio = 100 - Number.parseFloat(value);
      }
    },
    gtfyInputChanged(value) {
      this.form.cashRatio = 100 - value;
    },
    //--start-- 图片上传的状态出来
    //检测文件变动获取文件
    fileChange(file, fileList) {},

    //检测文件成功、删除 都先把原有清空，再重新赋值。
    fileRemove(file, fileList) {
      this.filesList = [];
      for (let index = 0; index < fileList.length; index++) {
        this.filesList.push(fileList[index].url);
      }
    },
    handleUploadSuccess(response, file, fileList) {
      this.filesList = [];
      for (let index = 0; index < fileList.length; index++) {
        if (fileList[index].response) {
          this.filesList.push(fileList[index].response.url);
        } else {
          this.filesList.push(fileList[index].url);
        }
      }
    },
    //--end--
    /** 通过 */
    pass() {
      this.form.status = 1;
      this.form.source = 2;
      let postage =
        Number.parseFloat(this.form.vipPrice) -
        Number.parseFloat(this.form.price);

      if (this.form.storeId === "" || this.form.storeId < 0) {
        this.$message.error("请先填写商家ID");
        return false;
      }

      if (this.isBlend) {
        if (this.form.passProportion == 0) {
          this.$message.error("请先填写混合比例");
          return false;
        }
      }

      let params = { ...this.form, postage };

      if (this.mode == "edit") {
        updateProducts(params).then((res) => {
          if (res.code == 200) {
            this.open = false;
            this.msgSuccess("审核通过");
          }
          this.getList();
        });
      } else {
        addProducts(params).then((res) => {
          if (res.code == 200) {
            this.open = false;
            this.msgSuccess("审核通过");
          }
          this.getList();
        });
      }
    },
    /** 拒绝*/
    refuse() {
      this.form.status = 0;
      this.form.source = 2;
      this.open = false;

      let postage =
        Number.parseFloat(this.form.vipPrice) -
        Number.parseFloat(this.form.price);
      let params = { ...this.form, postage, status: 0 };

      if (this.mode == "edit") {
        updateProducts(params).then((res) => {
          if (res.code == 200) {
            this.open = false;
            this.msgSuccess("已拒绝");
          }
          this.getList();
        });
      } else {
        addProducts(params).then((res) => {
          if (res.code == 200) {
            this.open = false;
            this.msgSuccess("已拒绝");
          }
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除商品信息编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delProducts(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有商品信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportProduct(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    /** 当关闭混合支付按钮时，gtfy支付比例归0 */
    payTypeChanged() {
      if (this.isBlend) {
        this.form.isBlend = 0;
        this.form.passProportion = 0;
        this.form.cashRatio = 100;
      } else {
        this.form.isBlend = 1;
        this.form.passProportion = 0;
        this.form.cashRatio = 100;
      }
    },
  },
};
</script>
<style>
.actualPay {
  width: 33%;
  text-align: center;
  margin-left: 6%;
  display: inline-block;
  color: white;
  background: #1890ff;
  font-weight: 600;
  border-radius: 4px;
}
</style>
